package tool.zyk.eventgroup;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * author: zyk
 * datetime: 2024/1/25 22:14
 * describe:
 */
@Slf4j
public class EventGroupServerTest {
    public static void main(String[] args) {
        DefaultEventLoopGroup normalWorkers=new DefaultEventLoopGroup(2);
        new ServerBootstrap()
                .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        nioSocketChannel.pipeline().addLast(normalWorkers,"myHandler",
                                new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(msg);
                                        ByteBuf byteBuf = msg instanceof ByteBuf ? (ByteBuf) msg : null;
                                        Optional.ofNullable(byteBuf).ifPresent(byt -> {
                                            byte[] buf = new byte[16];
                                            ByteBuf len = byt.readBytes(buf, 0, byt.readableBytes());
                                            log.info("传来的数据：{}", new String(buf));
                                        });
                                    }
                                }
                        );

                    }
                })
                .bind(8081);
    }
}
